package cn.ulyer.core.secure.authority.strategy;

import cn.ulyer.common.constants.AuthStrategyEnum;
import cn.ulyer.common.security.LoginUser;
import cn.ulyer.common.security.authority.AuthorityHandlerStrategy;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import javax.servlet.http.HttpServletRequest;

/**
 * 这里会默认匹配所有需要权限控制的 如果想自定义全部通过角色标识则可以加个前缀避免处理到其他自定义的
 */
public class DefaultHandlerStrategy implements AuthorityHandlerStrategy {

    final String split = ",";

    @Override
    public boolean handler(HttpServletRequest request, Authentication authentication, GrantedAuthority grantedAuthority) throws AccessDeniedException {
        if (!authentication.isAuthenticated()) {
            return false;
        }
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String[] authPerms = grantedAuthority.getAuthority().split(split);
            int result = 0;
            for (String authPerm : authPerms) {
                if (loginUser.hasPermission(authPerm)) {
                    ++result;
                }
            }
            return result > 0;
        }
        return false;
    }

    @Override
    public String strategy() {
        return AuthStrategyEnum.ANY_ROLE.name();
    }



}
